<?php
/**
 * appRain CMF
 *
 * LICENSE
 *
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/mit-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@apprain.com so we can send you a copy immediately.
 *
 * @copyright  Copyright (c) 2010 appRain, Team. (http://www.apprain.com)
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 *
 * HELP
 *
 * Official Website
 * http://www.apprain.com/
 *
 * Download Link
 * http://www.apprain.com/download
 *
 * Documents Link
 * http ://www.apprain.com/docs
 */
 
class Component_AuthorizeDotNet_Pgateway_AuthorizeDotNet extends Component_Appstore_Helpers_Pgateway_Common
{
	const CGI_URL = 'https://secure.authorize.net/gateway/transact.dll';
	const PAYMENT_SUCCESS_URL = '/payment-success';
	const PAYMENT_FAILED_URL = '/payment-failed';
	const VERSION = '3.1';
	const DELIM_DATA = 'TRUE';
	const DELIM_CHAR = "|";
	const RELAY_RESPONSE = "FALSE";
	const METHOD = 'cc';
	const STATUS_NAME = 'Authorize.Net';
	
	public function place()
	{
       $this->AssignPost()->Execute();
	}

	public function getStatusName()
	{
		return self::STATUS_NAME;
	}

	private function Assignpost()
	{
		$paymentData = $this->getPaymentData();		

		$paymentData['CardNo'] = isset($paymentData['CardNo']) ? $paymentData['CardNo'] : "";
		$month = $paymentData['expire_date']['month'];
		$year = (strlen($paymentData['expire_date']['year'])==4) ? substr($paymentData['expire_date']['year'],2,2) : $paymentData['expire_date']['year'];

		$authorizedotnet_mode = App::Helper('Config')->setting('authorizedotnet_mode','Production');
		$this->setXLogin(App::Helper('Config')->setting('authorizedotnet_login'))
			 ->setXTranKey(App::Helper('Config')->setting('authorizedotnet_tran_key'))
			 ->setXVersion(self::VERSION)
			 ->setXDelimData(self::DELIM_DATA)
			 ->setXDelimChar(self::DELIM_CHAR)
			 ->setXRelayResponse(self::RELAY_RESPONSE)
			 ->setXType(App::Helper('Config')->setting('authorizedotnet_tran_type','AUTH_CAPTURE'))
			 ->setXMethod(self::METHOD);

			if(strtoupper($authorizedotnet_mode) == "TEST"){
				$this->setXTestRequest('TRUE');
			}
			else{
				$this->setXTestRequest('FALSE');
			}

			$CardType = (isset($paymentData['CardType']) ? $paymentData['CardType'] : 'visa');
			if(App::Helper('Validation')->cc($paymentData['CardNo'],Array('type'=>$CardType))){
				$this->setXCardNum($paymentData['CardNo']);
			}
			else{
				throw new AppException($this->__('Invalid credit card information'));
			}

			$this->setXExpDate("{$month}{$year}");

			if($this->getAmount()>0){
				$this->setXAmount($this->getAmount());
			}
			else
			{
				throw new AppException($this->__('Invalid amount changed'));
			}

			$this->setXDescription($this->__("Sample Transaction"));

			$customer  = $this->getBillingAddress();
			$this->setXFirstName((isset($customer['fname'])?$customer['fname']:""))
			     ->setXLastName((isset($customer['lname'])?$customer['lname']:""))
			     ->setXAddress(
				 (isset($customer['address_line_1'])?$customer['address_line_1']:"") . ',' . 
				 (isset($customer['address_line_2'])?$customer['address_line_2']:"")
				 )
			     ->setXState((isset($customer['state'])?$customer['state']:""))			 
			     ->setXZip((isset($customer['zipcode'])?$customer['zipcode']:""))
			     ->setXCity((isset($customer['city'])?$customer['city']:""))
			     ->setXCountry((isset($customer['country'])?$customer['country']:""))
			     ->setXPhone((isset($customer['phoneno'])?$customer['phoneno']:""))
			     ->setXEmail((isset($customer['email'])?$customer['email']:""));
				 
			$customer  = $this->getShippingAddress();
			$this->setXShipFirstName((isset($customer['fname'])?$customer['fname']:""))
			     ->setXShipLastName((isset($customer['lname'])?$customer['lname']:""))
			     ->setXShipAddress(
				 (isset($customer['address_line_1'])?$customer['address_line_1']:"") . ',' .
				 (isset($customer['address_line_2'])?$customer['address_line_2']:"")
				 )
			     ->setXShipState((isset($customer['state'])?$customer['state']:""))			 
			     ->setXShipZip((isset($customer['zipcode'])?$customer['zipcode']:""))
			     ->setXShipCity((isset($customer['city'])?$customer['city']:""))
			     ->setXShipCountry((isset($customer['country'])?$customer['country']:""))
			     ->setXShipPhone((isset($customer['phoneno'])?$customer['phoneno']:""))
			     ->setXShipEmail((isset($customer['email'])?$customer['email']:""));				 

		return $this;
	}
	
	public function Execute()
	{

		$post_values = array(
			"x_login"		=> $this->getXLogin(),
			"x_tran_key"		=> $this->getXTranKey(),
			"x_version"		=> $this->getXVersion(),

			"x_test_request"	=> $this->getXTestRequest(),

			"x_delim_data"		=> $this->getXDelimData(),
			"x_delim_char"		=> $this->getXDelimChar(),
			"x_relay_response"	=> $this->getXRelayResponse(),

			"x_type"		=> $this->getXType(),
			"x_method"		=> $this->getXMethod(),
			"x_card_num"		=> $this->getXCardNum(),
			"x_exp_date"		=> $this->getXExpDate(),

			"x_amount"		=> $this->getXAmount(),
			"x_description"		=> $this->getXDescription(),

			"x_first_name"		=> $this->getXFirstName(),
			"x_last_name"		=> $this->getXLastName(),
			"x_address"		=> $this->getXAddress(),
			"x_state"		=> $this->getXState(),
			"x_zip"			=> $this->getXZip(),
			"x_city"		=> $this->getXCity(),
			"x_country"		=> $this->getXCountry(),
			"x_phone"		=> $this->getXPhone(),
			"x_email"		=> $this->getXEmail(),			
			

			"x_ship_to_first_name"		=> $this->getXShipFirstName(),
			"x_ship_to_last_name"		=> $this->getXShipLastName(),
			"x_ship_to_address"		=> $this->getXShipAddress(),
			"x_ship_to_state"		=> $this->getXShipState(),
			"x_ship_to_zip"			=> $this->getXShipZip(),
			"x_ship_to_city"		=> $this->getXShipCity(),
			"x_ship_to_country"		=> $this->getXShipCountry(),
			"x_ship_to_phone"		=> $this->getXShipPhone(),
			"x_ship_to_email"		=> $this->getXShipEmail(),
			
		);

		$post_string = "";
		foreach( $post_values as $key => $value ){
			$post_string .= "$key=" . urlencode( $value ) . "&"; 
		}
		$post_string = rtrim( $post_string, "& " );

		$cgi_url = App::Helper('Config')->setting('authorizedotnet_cgi_url',self::CGI_URL);
		$cgi_url = ($cgi_url!="")? $cgi_url :  self::CGI_URL;

		$request = curl_init($cgi_url); // initiate curl object
		curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
		curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
		curl_setopt($request, CURLOPT_POSTFIELDS, $post_string); // use HTTP POST to send form data
		curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response.
		$post_response = curl_exec($request); // execute curl post and store results in $post_response
		curl_close ($request);

		$response_array = explode($post_values["x_delim_char"],$post_response);
		$response_array[0] = isset($response_array[0]) ? $response_array[0] : "";
		if($response_array[0]!=1)
		{
			$response_array[3] = isset($response_array[3]) ? $response_array[3] : $this->__("Network is busy! Please try later") ;
			throw new AppException($this->__($response_array[3]));
		}
	}

    public function htmlToRender()
    {
        $cardTypes = array('visa'=>'Visa',"amex"=>"Amex","bankcard"=>"Bankcard","diners"=>"Diners","disc"=>"Disc","electron"=>"Electron","enroute"=>"Enroute","jcb"=>"JCB","maestro"=>"Maestro","mc"=>"Master Card","solo"=>"Solo","switch"=>"Switch","voyager"=>"Voyager");
        return 
		'<ul>
			<li>
				<label>Card No</label>
				<span>' . App::Helper('Html')->inputTag("data[Payment][authorizedotnet][CardNo]","",array("class"=>"input check_notdefault")) . '</span>
			</li>
			<li>
				<label>Card Type.</label>
				<span>' . App::Helper('Html')->selectTag("data[Payment][authorizedotnet][CardType]",$cardTypes,"visa",array("class"=>"check_notempty")) . '</span>
			</li>
			<li>
				<label>Exp Date</label>
				<span>' . App::Helper('Html')->ccExpireDate("data[Payment][authorizedotnet][expire_date]","",array("id"=>"expire_date")) . '</span>
			</li>
			<li>
				<label>CVV</label>
				<span>' . App::Helper('Html')->inputTag("data[Payment][authorizedotnet][cvv]","",array("class"=>"input check_notdefault")) . '</span>
			</li>
		</ul>
		<br class="clear" />';
    }
}